package binarytree;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/24 22:52
 * https://leetcode-cn.com/problems/convert-bst-to-greater-tree/
 * 把二叉搜索树转换为累加树
 */
public class ConvertBST {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    static int sum;

    /**
     * 递归法
     * @param root
     * @return
     */
    public TreeNode convertBST(TreeNode root) {
        sum = 0;
        if (root == null) {
            return null;
        }
        traversal(root);
        return root;
    }

    public static void traversal(TreeNode root) {
        if (root != null) {
            traversal(root.right);
            sum += root.val;
            root.val = sum;
            traversal(root.left);
        }
    }

    /**
     * 迭代法
     * @param root
     * @return
     */
    public static TreeNode convertBST1(TreeNode root) {
        sum = 0;
        if (root == null) {
            return null;
        }
        traversal1(root);
        return root;
    }

    public static void traversal1(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.right;
            }
            root = stack.pop();
            sum += root.val;
            root.val = sum;
            root = root.left;
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left = new TreeNode(1);
        TreeNode treeNode = convertBST1(root);
        System.out.println();
    }
}
